function varargout = vertical(varargin)
% VERTICAL M-file for vertical.fig
%      VERTICAL, by itself, creates a new VERTICAL or raises the existing
%      singleton*.
%
%      H = VERTICAL returns the handle to a new VERTICAL or the handle to
%      the existing singleton*.
%
%      VERTICAL('CALLBACK',hObject,eventData,handles,...) calls the local
%      function named CALLBACK in VERTICAL.M with the given input arguments.
%
%      VERTICAL('Property','Value',...) creates a new VERTICAL or raises the
%      existing singleton*.  Starting from the left, property value pairs are
%      applied to the GUI before vertical_OpeningFcn gets called.  An
%      unrecognized property name or invalid value makes property application
%      stop.  All inputs are passed to vertical_OpeningFcn via varargin.
%
%      *See GUI Options on GUIDE's Tools menu.  Choose "GUI allows only one
%      instance to run (singleton)".
%
% See also: GUIDE, GUIDATA, GUIHANDLES

% Edit the above text to modify the response to help vertical

% Last Modified by GUIDE v2.5 05-Dec-2011 14:48:37

% Begin initialization code - DO NOT EDIT
gui_Singleton = 1;
gui_State = struct('gui_Name',       mfilename, ...
                   'gui_Singleton',  gui_Singleton, ...
                   'gui_OpeningFcn', @vertical_OpeningFcn, ...
                   'gui_OutputFcn',  @vertical_OutputFcn, ...
                   'gui_LayoutFcn',  [] , ...
                   'gui_Callback',   []);
if nargin && ischar(varargin{1})
    gui_State.gui_Callback = str2func(varargin{1});
end

if nargout
    [varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:});
else
    gui_mainfcn(gui_State, varargin{:});
end
% End initialization code - DO NOT EDIT


% --- Executes just before vertical is made visible.
function vertical_OpeningFcn(hObject, eventdata, handles, varargin)
% This function has no output args, see OutputFcn.
% hObject    handle to figure
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
% varargin   command line arguments to vertical (see VARARGIN)

% Choose default command line output for vertical
handles.output = hObject;

% Update handles structure
guidata(hObject, handles);

% UIWAIT makes vertical wait for user response (see UIRESUME)
% uiwait(handles.figure1);


% --- Outputs from this function are returned to the command line.
function varargout = vertical_OutputFcn(hObject, eventdata, handles) 
% varargout  cell array for returning output args (see VARARGOUT);
% hObject    handle to figure
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Get default command line output from handles structure
varargout{1} = handles.output;


% --- Executes on button press in start_analyze.
function start_analyze_Callback(hObject, eventdata, handles)
% hObject    handle to start_analyze (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
%import data file
rawdata=importdata(get(handles.datafiledirectory,'String'));
c=str2double(get(handles.c_value,'String'));
mydata=rawdata.data;

%get individual columns
time=mydata(:,1);
magnet=mydata(:,2);
extension=mydata(:,3);
dx=mydata(:,4);
dy=mydata(:,5);

%plot timelapse curve
figure
plot(time,extension,'b-');
hold on
span = 50; % Size of the averaging window
window = ones(span,1)/span; 
smoothed_extension = convn(extension,window,'same');
plot(time,smoothed_extension,'r-');
legend('Data','Smoothed Data')
title('Time Lapse Extension');
xlabel('Time(s)');
ylabel('Extension(nm)');
hold off

%find when magnet were changed get segments of individual forces for
%processing
data_length=length(time);
flag_changeMagPosition=1;
position_magnetStart=-999;
MagnetPositions=zeros(0,4);
for i=1:data_length
    position_magnetCurrent=magnet(i);
    if position_magnetCurrent==position_magnetStart
        flag_changeMagPosition=0;
        count_magPosition=count_magPosition+1;
    else
        flag_changeMagPosition=1;
    end
    
    if flag_changeMagPosition==1
        if i~=1
            force_current=c*(exp(-(13.5-position_magnetStart)/0.36)+0.48*exp(-(13.5-position_magnetStart)/1.12));
            MagnetPositions=[MagnetPositions; [position_magnetStart point_positionStart count_magPosition force_current]];
        end
        point_positionStart=i;
        position_magnetStart=magnet(i);
        count_magPosition=0;    
    end
    if i==data_length
            force_current=c*(exp(-(13.5-position_magnetStart)/0.36)+0.48*exp(-(13.5-position_magnetStart)/1.12));
            MagnetPositions=[MagnetPositions; [position_magnetStart point_positionStart count_magPosition force_current]];
    end
end

%Get statistics at individual forces 
MatrixStatistics=zeros(0,8);
for i=1:length(MagnetPositions)
    extension_current=extension(MagnetPositions(i,2):MagnetPositions(i,2)+MagnetPositions(i,3));
    dx_current=dx(MagnetPositions(i,2):MagnetPositions(i,2)+MagnetPositions(i,3));
    dy_current=dy(MagnetPositions(i,2):MagnetPositions(i,2)+MagnetPositions(i,3));
    mean_extension_current=mean(extension_current);
    std_extension_current=std(extension_current);
    mean_dx_current=mean(dx_current);
    std_dx_current=std(dx_current);
    mean_dy_current=mean(dy_current);
    std_dy_current=std(dy_current);
    MatrixStatistics=[MatrixStatistics; [MagnetPositions(i,1) MagnetPositions(i,4) mean_extension_current std_extension_current mean_dx_current std_dx_current mean_dy_current std_dy_current]];
end

%Plot the force extension curve and force variance curve

%identify differet passes and assign them different color

colorprofile=zeros(length(MatrixStatistics),3);
color_current=1;
pass_current=1;
flag_peak=0;
position_peaks=1;

for i=1:length(MatrixStatistics)
    if (MatrixStatistics(i,1)>12) && (flag_peak==0)
        position_peak_start=i;
        flag_peak=1;
    else if (MatrixStatistics(i,1)<12) && (flag_peak==1)
            position_peak_end=i;
            flag_peak=0;
            peak_value=max(MatrixStatistics(position_peak_start:position_peak_end,1));
            for j=position_peak_start:position_peak_end
                if MatrixStatistics(j,1)==peak_value
                    tmp_peaks=j;
                end
            end
            if position_peaks(end)~=1
                low_peak_value=min(MatrixStatistics(position_peaks(end):tmp_peaks));
                for j=position_peaks(end):tmp_peaks
                    if MatrixStatistics(j,1)==low_peak_value
                        low_tmp_peaks=j;
                    end
                end
                position_peaks=[position_peaks;low_tmp_peaks];

            end
            position_peaks=[position_peaks;tmp_peaks];
            
        end
    end
end
colorlist=jet(length(position_peaks));
for i=1:(length(position_peaks)-1)
    colorprofile(position_peaks(i):position_peaks(i+1),:)=repmat(colorlist(color_current,:),length(colorprofile(position_peaks(i):position_peaks(i+1),:)),1);
    color_current=color_current+1;
end
colorprofile(position_peaks(end):end,:)=repmat(colorlist(color_current,:),length(colorprofile(position_peaks(end):end,:)),1);


%plot force fluctuation and force extension curves
scatter(handles.axes1,MatrixStatistics(:,2),MatrixStatistics(:,3),10,colorprofile,'filled')
title('Force vs Extension');
xlabel('Forces (pN)');
ylabel('Extension (nm)');
scatter(handles.axes2,MatrixStatistics(:,2),MatrixStatistics(:,5),10,colorprofile,'filled')
title('Force vs dx');
xlabel('Forces (pN)');
ylabel('mean dx (nm)');
scatter(handles.axes3,MatrixStatistics(:,2),MatrixStatistics(:,7),10,colorprofile,'filled')
title('Force vs dy');
xlabel('Forces (pN)');
ylabel('mean dy (nm)');

figure
subplot(2,2,1)
scatter(MatrixStatistics(:,2),MatrixStatistics(:,4),10,colorprofile,'filled')
title('Force vs stdZ');
xlabel('Forces (pN)');
ylabel('stdZ (nm)');

subplot(2,2,2)
scatter(MatrixStatistics(:,2),MatrixStatistics(:,6),10,colorprofile,'filled')
title('Force vs stdX');
xlabel('Forces (pN)');
ylabel('stdX (nm)');
subplot(2,2,3)
scatter(MatrixStatistics(:,2),MatrixStatistics(:,8),10,colorprofile,'filled')
title('Force vs stdY');
xlabel('Forces (pN)');
ylabel('stdY (nm)');

% subplot(2,4,8)
% scatter(MatrixStatistics(5,3),MatrixStatistics(5,5),10,colorprofile,'filled')
% title('Extension vs dx');
% xlabel('Forces (pN)');
% ylabel('stdY (nm)');
%checking the unfolding signals find the points where the mean unfolding
%peaks are over certain point

window_size=100;
threshold=5;
flag_step=0;
step_list=zeros(0,4);
unfold_list=zeros(0,4);
refold_list=zeros(0,4);
step_diff_max=0;
for i=1:length(MagnetPositions)
    extension_current=extension(MagnetPositions(i,2):MagnetPositions(i,2)+MagnetPositions(i,3));
    for j=(window_size+1):(length(extension_current)-window_size)
        previous=mean(extension_current((j-window_size):j));
        later=mean(extension_current(j:(j+window_size)));
        step_diff_current=later-previous;
        if abs(step_diff_current)>threshold 
                flag_step=1;
        end
        if flag_step==1
            if abs(step_diff_current)<=threshold 
                flag_step=0;
                step_list=[step_list;[MagnetPositions(i,1) MagnetPositions(i,4) step_position step_diff_max]];
                if step_diff_max>0
                    unfold_list=[unfold_list;[MagnetPositions(i,1) MagnetPositions(i,4) step_position step_diff_max]];
                else
                    refold_list=[refold_list;[MagnetPositions(i,1) MagnetPositions(i,4) step_position abs(step_diff_max)]];
                end
                step_diff_max=0;
            else
                if abs(step_diff_current)>abs(step_diff_max)
                    step_diff_max=step_diff_current;
                    step_position=MagnetPositions(i,2)+j-1;
                end
            end
            
        end
    end
end

%plot histogram of the stepsizes

%define bin sizes by indicating the center for each bin
histcenters={0:2:30 0:1:20};

X=[step_list(:,4) step_list(:,2)];
UNfold=[unfold_list(:,4) unfold_list(:,2)];
REfold=[refold_list(:,4) refold_list(:,2)];
figure
subplot(2,2,1)
hist3(X,histcenters)
title('Steps');
xlabel('Step size'); ylabel('Force');
set(gcf,'renderer','opengl');
set(get(gca,'child'),'FaceColor','interp','CDataMode','auto');

subplot(2,2,2)
hist3(UNfold,histcenters)
title('Unfold Steps');
xlabel('Step size'); ylabel('Force');
set(gcf,'renderer','opengl');
set(get(gca,'child'),'FaceColor','interp','CDataMode','auto');

subplot(2,2,3)
hist3(REfold,histcenters)
title('REfold Steps');
xlabel('Step size'); ylabel('Force');
set(gcf,'renderer','opengl');
set(get(gca,'child'),'FaceColor','interp','CDataMode','auto');



% --- Executes on button press in Browse_data_file.
function Browse_data_file_Callback(hObject, eventdata, handles)
% hObject    handle to Browse_data_file (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
[datafile_filename,datafile_directory]=uigetfile;
set(handles.datafiledirectory,'String',[datafile_directory datafile_filename]);
set(handles.notefiledirectory,'String',[datafile_directory strrep(datafile_filename,'.txt','-note.txt')]);




function datafiledirectory_Callback(hObject, eventdata, handles)
% hObject    handle to datafiledirectory (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'String') returns contents of datafiledirectory as text
%        str2double(get(hObject,'String')) returns contents of datafiledirectory as a double


% --- Executes during object creation, after setting all properties.
function datafiledirectory_CreateFcn(hObject, eventdata, handles)
% hObject    handle to datafiledirectory (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: edit controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end



function notefiledirectory_Callback(hObject, eventdata, handles)
% hObject    handle to notefiledirectory (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'String') returns contents of notefiledirectory as text
%        str2double(get(hObject,'String')) returns contents of notefiledirectory as a double


% --- Executes during object creation, after setting all properties.
function notefiledirectory_CreateFcn(hObject, eventdata, handles)
% hObject    handle to notefiledirectory (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: edit controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end


% --- Executes on selection change in magnettype.
function magnettype_Callback(hObject, eventdata, handles)
% hObject    handle to magnettype (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: contents = cellstr(get(hObject,'String')) returns magnettype contents as cell array
%        contents{get(hObject,'Value')} returns selected item from magnettype



% --- Executes during object creation, after setting all properties.
function magnettype_CreateFcn(hObject, eventdata, handles)
% hObject    handle to magnettype (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: popupmenu controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end
set(handles.magnettype,'Value',1);




function overstretching_position_Callback(hObject, eventdata, handles)
% hObject    handle to overstretching_position (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'String') returns contents of overstretching_position as text
%        str2double(get(hObject,'String')) returns contents of overstretching_position as a double
overstretch_postion=str2double(get(hObject,'String'))/1000;
mag_type=get(handles.magnettype,'Value');
if mag_type == 1
    c_value=65/(exp(-(13.5-overstretch_postion)/0.36)+0.48*exp(-(13.5-overstretch_postion)/1.12));
else
    c_value=65/(exp(-(13.5-overstretch_postion)/0.36)+0.48*exp(-(13.5-overstretch_postion)/1.12));
end
set(handles.c_value,'String',c_value);



% --- Executes during object creation, after setting all properties.
function overstretching_position_CreateFcn(hObject, eventdata, handles)
% hObject    handle to overstretching_position (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: edit controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end



function c_value_Callback(hObject, eventdata, handles)
% hObject    handle to c_value (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'String') returns contents of c_value as text
%        str2double(get(hObject,'String')) returns contents of c_value as a double


% --- Executes during object creation, after setting all properties.
function c_value_CreateFcn(hObject, eventdata, handles)
% hObject    handle to c_value (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: edit controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end


% --- Executes when figure1 is resized.
function figure1_ResizeFcn(hObject, eventdata, handles)
% hObject    handle to figure1 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)


% --- Executes on slider movement.
function slider1_Callback(hObject, eventdata, handles)
% hObject    handle to slider1 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'Value') returns position of slider
%        get(hObject,'Min') and get(hObject,'Max') to determine range of slider


% --- Executes during object creation, after setting all properties.
function slider1_CreateFcn(hObject, eventdata, handles)
% hObject    handle to slider1 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: slider controls usually have a light gray background.
if isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor',[.9 .9 .9]);
end
